//
//  AIQuestionViewController.swift
//  AIImage
//
//  Created by deng on 2023/12/10.
//

import UIKit
import Alamofire

class AIQuestionViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    lazy var tableView:UITableView = {
        let tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        return tableView
    }()
    
    var fatherM = AISaveModel()
    var detailM = AIModel()
    let textF = UITextField.init()
    var dataList = [AIListModel]()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if #available(iOS 15.0, *) {
            let barAppearance = UINavigationBarAppearance.init()
            barAppearance.backgroundColor = .clear
            navigationController?.navigationBar.scrollEdgeAppearance = nil
            navigationController?.navigationBar.standardAppearance = barAppearance
        } else {
            navigationController?.navigationBar.barTintColor = .clear
            navigationController?.navigationBar.shadowImage = UIImage()
            navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        }
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.tintColor = .clear
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 11.0, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        edgesForExtendedLayout = .top
        
        let leftBtn = UIButton()
        leftBtn.setImage(UIImage(named: "back_icon"), for: .normal)
        leftBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBtn)
        leftBtn.addTarget(self, action: #selector(goBack), for: .touchUpInside)

        // Do any additional setup after loading the view.
        let bgView = UIImageView.init(image: UIImage(named: "bg_icon"))
        bgView.frame = view.bounds
        bgView.isUserInteractionEnabled = true
        bgView.contentMode = .scaleAspectFill
        view.addSubview(bgView)
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.width.top.equalToSuperview()
            make.bottom.equalTo(-112*DS.s-kBottomHeight)
        }
        tableView.register(cellType: AIQuestionTopTableViewCell.self)
        tableView.register(cellType: AiQuestionListTableViewCell.self)
        
        let bottomView = UIView.init()
        bottomView.backgroundColor = .hexString("#313131")
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.width.equalToSuperview()
            make.height.equalTo(112*DS.s)
            make.bottom.equalTo(-kBottomHeight)
        }
        
        textF.placeholder = "请输入你想知道的问题"
        textF.text = detailM.qs ?? ""
        textF.font = .systemFont(ofSize: 18, weight: .bold)
        textF.textColor = .white
        bottomView.addSubview(textF)
        textF.snp.makeConstraints { make in
            make.left.top.equalTo(20*DS.s)
            make.right.equalTo(-20*DS.s)
            make.height.equalTo(24*DS.s)
        }
        
        let lineV = UIView.init()
        lineV.backgroundColor = .hexString("#878787")
        bottomView.addSubview(lineV)
        lineV.snp.makeConstraints { make in
            make.left.right.equalTo(textF)
            make.top.equalTo(textF.snp.bottom).offset(4*DS.s)
            make.height.equalTo(1*DS.s)
        }
        
        let questionBtn = UIButton.init()
        questionBtn.setTitle("问问我", for: .normal)
        questionBtn.titleLabel?.font = .systemFont(ofSize: 18, weight: .bold)
        questionBtn.setTitleColor(.white, for: .normal)
        questionBtn.backgroundColor = .hexString("#ff8218")
        bottomView.addSubview(questionBtn)
        questionBtn.snp.makeConstraints { make in
            make.right.equalTo(-10*DS.s)
            make.top.equalTo(lineV.snp.bottom).offset(16*DS.s)
            make.left.equalTo(10*DS.s)
            make.height.equalTo(34*DS.s)
        }
        questionBtn.addTarget(self, action: #selector(questionClick), for: .touchUpInside)
        questionBtn.layer.cornerRadius = 5
        questionBtn.layer.masksToBounds = true
        
    }
    
    @objc func questionClick(){
        
        let str = textF.text ?? ""
        if str == ""{
            self.view.makeToast("请输入你想知道的问题")
            return
        }
        let loadingView = LoadingView(frame: CGRect(x: KScreenWidth/2-70*DS.s, y: KScreenHeight/2-50*DS.s, width: 140*DS.s, height: 100*DS.s), text: "AI加载中...")
        view.addSubview(loadingView)
        let url = "https://img-identify-qs-axrxhqrjus.cn-hangzhou.fcapp.run/qs?target=\(fatherM.name ?? "")&text=\(str)"
        AF.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { response in
            loadingView.stopLoading()
            switch response.result {
            case let .success(json):
                if let err = response.error {
                } else {
                    let dict = json
                    if let dic = dict as? NSDictionary {
                        self.textF.text = ""
                        let model = AIListModel.deserialize(from: dic) ?? AIListModel()
                        model.question = str
                        self.dataList.append(model)
                        self.tableView.reloadData()
                        let lastRowIndex = self.tableView.numberOfRows(inSection: 0) - 1
                        let lastRowIndexPath = IndexPath(row: lastRowIndex, section: 0)
                        self.tableView.scrollToRow(at: lastRowIndexPath, at: .bottom, animated: true)
                    }
                }
            case let .failure(errorD):
                print("出错啦:\(errorD)")
            }
        }
        
    }
    
    @objc func goBack(){
        
        navigationController?.popViewController(animated: true)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataList.count+1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row > 0{
            let cell: AiQuestionListTableViewCell = tableView.dequeueReusableCell(for: indexPath)
            let vo = dataList[indexPath.row-1]
            cell.setupData(vo: vo)
            return cell
        }
        let cell: AIQuestionTopTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        cell.setupData(fatherM: fatherM, vo: detailM)
        return cell
    }
}
